package indi.jp.project.core.controller;

import indi.jp.project.core.entity.JsonResult;
import indi.jp.project.core.entity.Permission;
import indi.jp.project.core.service.PermissionService;
import indi.jp.project.core.util.SimpleEntityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @GetMapping("/queryGrid")
    @ResponseBody
    public JsonResult queryGrid(@ModelAttribute Permission entity){
        int offset = (entity.getPage() - 1) * entity.getPageSize();
        entity.setOffset(offset);
        try {
            Map<String, Object> map = permissionService.queryGrid(entity);
            return JsonResult.success(map);
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @PostMapping("/save")
    @ResponseBody
    public JsonResult save(@RequestBody Permission entity, HttpServletRequest request) {
        SimpleEntityUtil<Permission> simpleEntityUtil = new SimpleEntityUtil<>();
        entity = simpleEntityUtil.setBaseEntity(entity, request);
        try {
            return permissionService.save(entity);
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @PostMapping("/deleteById")
    @ResponseBody
    public JsonResult deleteById(HttpServletRequest request){
        String id = request.getParameter("id");
        try {
            int effectRow = permissionService.deleteById(id);
            if(effectRow > 0){
                return JsonResult.success("");
            } else {
                return JsonResult.failure("未能成功删除，请刷新查看数据是否存在");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @GetMapping("/queryPermissions")
    @ResponseBody
    public JsonResult queryPermissions(){
        // 这边应该需要查询企业的权限列表，后续完善
        return permissionService.queryPermissions();
    }

    @PostMapping("/savePermissions")
    @ResponseBody
    public JsonResult savePermissions(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        try {
            permissionService.savePermissions(map);
            return JsonResult.success("");
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @GetMapping("/queryRolePermissions")
    @ResponseBody
    public JsonResult queryRolePermissions(HttpServletRequest request){
        String roleId = request.getParameter("roleId");
        return permissionService.queryRolePermissions(roleId);
    }

}
